package com.rytx.common.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class AmountUtils {
    /**
     * 元转分，确保price保留两位有效数字
     * @return
     */
    public static int changeY2F(double price) {
        DecimalFormat df = new DecimalFormat("#.00");
        price = Double.valueOf(df.format(price));
        int money = (int)(price * 100);
        return money;
    }

    /**
     * 元转换成分
     * @param money
     * @return
     */
    public static Long getMoney(String amount) {
        if(amount==null){
            return 0l;
        }
        // 金额转化为分为单位
        String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if(index == -1){
            amLong = Long.valueOf(currency+"00");
        }else if(length - index >= 3){
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
        }else if(length - index == 2){
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
        }else{
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
        }
        return amLong;
    }

    /**
     * 分转元，转换为bigDecimal在toString
     * @return
     */
    public static String changeF2Y(int price) {
        return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100),2, RoundingMode.HALF_UP).toString();
    }
    /**
     * 分转元，转换为bigDecimal在toString
     * @return
     */
    public static String changeF2Y(Long price) {
        return BigDecimal.valueOf(price).divide(new BigDecimal(100),2, RoundingMode.HALF_UP).toString();
    }
    /**
     * 分转元，转换为bigDecimal在转成double
     * @return
     */
    public static BigDecimal changeF2Y3(int price) {
        return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100),2);
    }

}
